<template>
  <div class="product-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <el-button type="primary" @click="showModal">
            <el-icon><Plus /></el-icon>
            添加商品
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="productList"
        style="width: 100%"
      >
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="120" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleBuy(row)"
              >
                购买
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 商品表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formState.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="formState.price"
            :precision="2"
            :step="0.1"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number
            v-model="formState.stock"
            :precision="0"
            :step="1"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="formState.categoryId" style="width: 100%">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <el-input v-model="formState.imageUrl" placeholder="请输入商品图片URL" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="formState.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 购买商品对话框 -->
    <el-dialog
      v-model="buyDialogVisible"
      title="购买商品"
      width="500px"
    >
      <el-form
        ref="buyFormRef"
        :model="buyFormState"
        :rules="buyRules"
        label-width="100px"
      >
        <el-form-item label="商品名称">
          <el-input v-model="selectedProduct.name" disabled />
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="selectedProduct.price" disabled />
        </el-form-item>
        <el-form-item label="购买数量" prop="quantity">
          <el-input-number
            v-model="buyFormState.quantity"
            :precision="0"
            :step="1"
            :min="1"
            :max="selectedProduct.stock"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="buyFormState.receiverName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="receiverPhone">
          <el-input v-model="buyFormState.receiverPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="收货地址" prop="receiverAddress">
          <el-input
            v-model="buyFormState.receiverAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入收货地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="buyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBuySubmit">
            提交订单
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const store = useStore()
const loading = ref(false)
const dialogVisible = ref(false)
const buyDialogVisible = ref(false)
const dialogType = ref('add')
const productList = ref([])
const categoryList = ref([])
const formRef = ref()
const buyFormRef = ref()
const selectedProduct = ref({})

const formState = reactive({
  id: null,
  name: '',
  price: 0,
  stock: 0,
  categoryId: null,
  imageUrl: '',
  description: ''
})

const buyFormState = reactive({
  quantity: 1,
  receiverName: '',
  receiverPhone: '',
  receiverAddress: ''
})

const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  imageUrl: [
    { required: true, message: '请输入商品图片URL', trigger: 'blur' }
  ]
}

const buyRules = {
  quantity: [
    { required: true, message: '请输入购买数量', trigger: 'blur' }
  ],
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  receiverAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ]
}

const fetchProducts = async () => {
  try {
    loading.value = true
    const data = await store.dispatch('product/getProducts')
    productList.value = data
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const fetchCategories = async () => {
  try {
    const data = await store.dispatch('category/getCategories')
    categoryList.value = data
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  }
}

const resetForm = () => {
  formState.id = null
  formState.name = ''
  formState.price = 0
  formState.stock = 0
  formState.categoryId = null
  formState.imageUrl = ''
  formState.description = ''
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const resetBuyForm = () => {
  buyFormState.quantity = 1
  buyFormState.receiverName = ''
  buyFormState.receiverPhone = ''
  buyFormState.receiverAddress = ''
  if (buyFormRef.value) {
    buyFormRef.value.resetFields()
  }
}

const showModal = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formState, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该商品吗？删除后无法恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await store.dispatch('product/deleteProduct', row.id)
      ElMessage.success('删除成功')
      fetchProducts()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleBuy = (row) => {
  selectedProduct.value = row
  resetBuyForm()
  buyDialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await store.dispatch('product/createProduct', formState)
      ElMessage.success('添加成功')
    } else {
      await store.dispatch('product/updateProduct', formState)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchProducts()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

const handleBuySubmit = async () => {
  if (!buyFormRef.value) return
  
  try {
    await buyFormRef.value.validate()
    await store.dispatch('order/createOrder', {
      productId: selectedProduct.value.id,
      quantity: buyFormState.quantity,
      receiverName: buyFormState.receiverName,
      receiverPhone: buyFormState.receiverPhone,
      receiverAddress: buyFormState.receiverAddress
    })
    ElMessage.success('订单提交成功')
    buyDialogVisible.value = false
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

onMounted(() => {
  fetchProducts()
  fetchCategories()
})
</script>

<style lang="scss" scoped>
.product-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 